import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, message } from 'antd';
import React from 'react';
import './index.css';
import { Token, homeUrl } from '../../../utils/const.ts';
import { useHistory } from 'react-router-dom'
const Login = () => {
  const history = useHistory();
  const onFinish = async (values) => {
    console.log('values==', values);
    try {
      const response = await fetch('/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          mobilephone: values.mobilephone,
          password: values.password,
        }),
      });
      const data = await response.json();
      if (data.code === 200) {
        // 登录成功，可以在这里处理跳转逻辑或者保存token等
        window.localStorage.setItem(Token, data.data.tokenStr);
        window.localStorage.setItem('loginRes', JSON.stringify(data.data));
        message.success('登录成功!');
        history.push(homeUrl);
        window.location.reload();
      } else {
        message.error(`登录失败: ${data.msg || data.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('Login error:', error);
      alert('登录请求失败，请检查网络或服务器！');
    }
  };
  return (
    <div className='login-wrap'>
      <Form
        name="normal_login"
        className="login-form"
        layout="horizontal" // 关键点
        labelCol={{ span: 0 }} // label 占 6/24
        wrapperCol={{ span: 24 }} // 输入框占 18/24
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
      >
        <h1 className='login-title'>证书认证系统</h1>
        <Form.Item
          name="mobilephone"
          rules={[
            {
              required: true,
              message: '请输入你的用户名!',
            },
          ]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入你的密码!',
            },
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
          />
        </Form.Item>
        <Form.Item name="remember" valuePropName="checked">
          <Checkbox>记住我</Checkbox>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登  录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
export default Login;